package com.jzg.jcptadmin.ui;


import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.jzg.jcptadmin.R;
import com.jzg.jcptadmin.Utils.MD5Utils;
import com.jzg.jcptadmin.Utils.MyToast;
import com.jzg.jcptadmin.adpter.AdmixedLeftAdapter;
import com.jzg.jcptadmin.adpter.AdmixedRightAdapter;
import com.jzg.jcptadmin.app.AppContext;
import com.jzg.jcptadmin.base.BaseActivity;
import com.jzg.jcptadmin.data.DataManager;
import com.jzg.jcptadmin.data.vo.AdmixedData;
import com.jzg.jcptadmin.data.vo.NewStyle;
import com.jzg.jcptadmin.presenter.CarParamConfigPresenter;
import com.jzg.jcptadmin.view.CarStyleConfirmDialog;
import com.jzg.jcptadmin.view.CustomRippleButton;
import com.jzg.jcptadmin.view.MyHorizontalItem;
import com.jzg.jcptadmin.view.MySyncHorizontalScrollView;
import com.jzg.jcptadmin.view.ScrollBottomScrollView;
import com.jzg.jcptadmin.viewinterface.IAdmixedInf;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import butterknife.ButterKnife;
import me.everything.android.ui.overscroll.OverScrollDecoratorHelper;
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

/**
 * author: guochen
 * date: 2016/11/1 15:13
 * modified by zealjiang 2016/12/11
 * 参配列表
 */
public class AdmixedContrastActivity extends BaseActivity implements IAdmixedInf,MyHorizontalItem.MyCloseOnClickListener, MyHorizontalItem.MyOkOnClickListener, View.OnClickListener {

    @Bind(R.id.title_content)
    TextView titleContent;
    @Bind(R.id.title_return)
    ImageView titleReturn;
    @Bind(R.id.tv_zhaopianbidui)
    CustomRippleButton crbPicCompare;
    @Bind(R.id.title)
    RelativeLayout title;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.ll_hrz)
    LinearLayout llHrz;
    @Bind(R.id.mytable_scrollview)
    MySyncHorizontalScrollView mytableScrollview;
    @Bind(R.id.contentListViewLeft)
    XRecyclerView contentListViewLeft;
    @Bind(R.id.contentListViewRight)
    XRecyclerView contentListViewRight;
    @Bind(R.id.rightContentHorscrollView)
    MySyncHorizontalScrollView rightContentHorscrollView;
    @Bind(R.id.tv_show_all)
    TextView tvShowAll;
    @Bind(R.id.scrollBottomScrollView)
    ScrollBottomScrollView scrollBottomScrollView;

    private ArrayList<String> styleids;
    private AdmixedData admixedData;
    private String IsDiff = "1";//1差异项 0全部
    private String styleIdsParam;//请求的styleid用|分割
    private CarParamConfigPresenter carParamConfigPresenter;
    private AdmixedLeftAdapter admixedLeftAdapter;
    private AdmixedRightAdapter admixedRightAdapter;
    private List<AdmixedData.ShowDataBean> showDataList;
    private final int loadNum = 15;
    private Subscription subscribe;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_admixed);
        ButterKnife.bind(this);
        carParamConfigPresenter = new CarParamConfigPresenter(DataManager.getInstance());
        carParamConfigPresenter.attachView(this);
        titleContent.setText("车辆参配");
        Intent intent = getIntent();
        //请求的styleid用|分割
        styleids = intent.getStringArrayListExtra("styleIds");
        if (styleids == null || styleids.size() == 0) {
            Toast.makeText(this, "请选择车型", Toast.LENGTH_SHORT).show();
            return;
        }
        showDataList = new ArrayList<>();
        initView();
        startAlreadyListThread();
//        wait2s();
    }



    private String FilterData() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < styleids.size(); i++) {
            sb.append(styleids.get(i) + "|");
        }
        sb.deleteCharAt(sb.length()-1);
        styleIdsParam = sb.toString();
        //TODO
//        styleIdsParam = "121280|121281|121282|121283|121284|116742|116743|120256|116744|118384|118385|116745|116746";
        return styleIdsParam;
    }


    private void initView() {
        //	参配列表默认显示隐藏相同参配，此时，按钮为“显示全部参配”按钮，点击“显示全部参配”按钮后，按钮状态改变为“隐藏相同配置”，此时列表未全部参配；
        tvShowAll.setText("显示全部参配");
        tvShowAll.setOnClickListener(this);
        crbPicCompare.setOnClickListener(this);
        OverScrollDecoratorHelper.setUpOverScroll(mytableScrollview);
        OverScrollDecoratorHelper.setUpOverScroll(rightContentHorscrollView);
        mytableScrollview.setmSyncView(rightContentHorscrollView);
        rightContentHorscrollView.setmSyncView(mytableScrollview);
        //syncScroll(contentListViewLeft,contentListViewRight);

    }

    private void initLeftRecyclerView(){
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        contentListViewLeft.setNestedScrollingEnabled(false);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        contentListViewLeft.setLayoutManager(layoutManager);
        contentListViewLeft.setPullRefreshEnabled(true);
        contentListViewLeft.setLoadingMoreEnabled(true);

    }

    private void initRightRecyclerView(){
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        contentListViewRight.setNestedScrollingEnabled(false);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        contentListViewRight.setLayoutManager(layoutManager);
        contentListViewRight.setPullRefreshEnabled(false);
    }

    private void initData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        llHrz.removeAllViews();
                        for (int i = 0; i < admixedData.getCarData().size(); i++) {
                            MyHorizontalItem myHorizontalItem = new MyHorizontalItem(AdmixedContrastActivity.this);
                            myHorizontalItem.setPosition(i);
                            myHorizontalItem.setContent(admixedData.getCarData().get(i).getStyleName());
                            myHorizontalItem.setGuidePrice(admixedData.getCarData().get(i).getNowMsrp()+"万元");
                            llHrz.addView(myHorizontalItem);
                            myHorizontalItem.setMyCloseOnClickListener(AdmixedContrastActivity.this);
                            myHorizontalItem.setMyOkOnClickListener(AdmixedContrastActivity.this);
                        }

                        initRecyclerView();

                    }
                });
            }
        }).start();


    }

    private void initRecyclerView(){

        showDataList = admixedData.getShowData();
        initLeftRecyclerView();
        admixedLeftAdapter = new AdmixedLeftAdapter(AdmixedContrastActivity.this, showDataList);
        contentListViewLeft.setAdapter(admixedLeftAdapter);
        admixedLeftAdapter.notifyDataSetChanged();

        initRightRecyclerView();
        admixedRightAdapter = new AdmixedRightAdapter(AdmixedContrastActivity.this, showDataList,admixedData.getCarData().size());
        contentListViewRight.setAdapter(admixedRightAdapter);
        admixedRightAdapter.notifyDataSetChanged();

        contentListViewRight.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right,
                                       int bottom, int oldLeft, int oldTop, int oldRight,
                                       int oldBottom) {
                if (contentListViewRight.getChildCount()!=0) {
                    dismissDialog();
                }
            }
        });
    }

    @Override
    public void onCloseClickListener(View view, int position) {
        showDialog();
        wait1s(position);
    }

    private void wait1s(final int position){
        subscribe = Observable.timer(1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Long>() {
                    @Override
                    public void call(Long aLong) {
                        //----------test data--------------------
//                        startAlreadyListThread();
                        getDialog().getProgressHelper().hideProgress();
                        getDialog().setContentText("正在删除数据 请耐心等待...");

                        if(position<admixedData.getCarData().size()){
                            if(admixedData.getCarData().size()==1){//最后一个不能关闭
                                return;
                            }
                            //删除对应的车辆
                            admixedData.getCarData().remove(position);
                            //删除对应的view
                            llHrz.removeViewAt(position);
                            //重新设置车辆的position
                            for (int i = 0; i < admixedData.getCarData().size(); i++) {
                                ((MyHorizontalItem)llHrz.getChildAt(i)).setPosition(i);
                            }

                            //删除对应的图片
                            for (int i = 0; i < admixedData.getPhotoData().size(); i++) {
                                admixedData.getPhotoData().get(i).getPropertyValue().remove(position);
                            }
                            //删除对应的参数
                            for (int i = 0; i < admixedData.getShowData().size(); i++) {
                                if(admixedData.getShowData().get(i).getDataType()==1){
                                    admixedData.getShowData().get(i).getPropertyValue().remove(position);
                                }
                            }
                        }

                        admixedLeftAdapter.notifyDataSetChanged();
                        contentListViewLeft.scrollToPosition(0);
                        admixedRightAdapter = new AdmixedRightAdapter(AdmixedContrastActivity.this, showDataList,admixedData.getCarData().size());
                        contentListViewRight.setAdapter(admixedRightAdapter);
                        //---------------------------------------
                    }
                });
    }

    @Override
    public void onOkClickListener(View view, int position) {
        if (position < admixedData.getCarData().size()) {
            NewStyle newStyle = new NewStyle();
            newStyle.setName(admixedData.getCarData().get(position).getStyleName());
            newStyle.setNowMsrp(admixedData.getCarData().get(position).getNowMsrp()+"");
            newStyle.setStyleId(admixedData.getCarData().get(position).getStyleID()+"");

            String content = "您已选择" + newStyle.getName() + "款车型\n指导价" + newStyle.getNowMsrp() + "万,请确认这是否为您所需要的车型";
            CarStyleConfirmDialog carStyleConfirmDialog = new CarStyleConfirmDialog(AdmixedContrastActivity.this);
            carStyleConfirmDialog.setData(content,newStyle);
            carStyleConfirmDialog.createDialog();

        }
    }

    public void startAlreadyListThread() {
        showDialog();
        if (TextUtils.isEmpty(FilterData())) {
            Toast.makeText(this, "请选择车型", Toast.LENGTH_SHORT).show();
            return;
        }
        if(!AppContext.isNetWork){
            MyToast.showShort(getResources().getString(R.string.check_net));
            return;
        }
        carParamConfigPresenter.requestAdmixedData();
        //----------test data--------------------
//        String carType="";
//        if (IsDiff.equals("0")) {
//            carType = StringUtil.getFromAssets("cartypeall.txt", this);
//        }else if (IsDiff.equals("1")){
//            carType = StringUtil.getFromAssets("cartypehide.txt", this);
//        }
//        ResponseJson<AdmixedData> responseJson = new Gson().fromJson(carType, new TypeToken<ResponseJson<AdmixedData>>(){}.getType());
//        AdmixedData admixedData = responseJson.getMemberValue();
//        AdmixedContrastActivity.this.admixedData = admixedData;
//        initData();

        //---------------------------------------

    }


    public void goBack(View view) {
        finish();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_show_all:
                if ("显示全部参配".equals(tvShowAll.getText().toString().trim())) {
                    tvShowAll.setText("隐藏相同配置");
                    tvShowAll.setBackgroundColor(getResources().getColor(R.color.red));
                    //要显示全部配置
                    IsDiff = "0";
                    startAlreadyListThread();
                } else {
                    tvShowAll.setText("显示全部参配");
                    tvShowAll.setBackgroundColor(getResources().getColor(R.color.common_btn_blue));
                    IsDiff = "1";
                    startAlreadyListThread();
                }
                break;
            case R.id.tv_zhaopianbidui:
//                if(!AppContext.isNetWork){
//                    MyToast.showShort(getResources().getString(R.string.check_net));
//                    return;
//                }
//                if(admixedData==null){
//                    MyToast.showShort("车辆数据不可为空");
//                    return;
//                }
//                Intent intent = new Intent(this, CarPicComparedActivity.class);
//                intent.putExtra(Constants.ADMIXEDCONTRASTACTIVITY, admixedData);
//                startActivityForResult(intent, 1);
                break;

            default:

                break;
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (subscribe!=null)
        subscribe.unsubscribe();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                if (data != null) {
                    this.admixedData = (AdmixedData)data.getSerializableExtra("AdmixedData");
                    refresh();
                }
                break;
            default:

                break;
        }
    }

    private void refresh(){
        llHrz.removeAllViews();
        for (int i = 0; i < admixedData.getCarData().size(); i++) {
            MyHorizontalItem myHorizontalItem = new MyHorizontalItem(AdmixedContrastActivity.this);
            myHorizontalItem.setPosition(i);
            myHorizontalItem.setContent(admixedData.getCarData().get(i).getStyleName());
            myHorizontalItem.setGuidePrice(admixedData.getCarData().get(i).getNowMsrp()+"");
            llHrz.addView(myHorizontalItem);
            myHorizontalItem.setMyCloseOnClickListener(AdmixedContrastActivity.this);
            myHorizontalItem.setMyOkOnClickListener(AdmixedContrastActivity.this);
        }

        initRecyclerView();
    }

    @Override
    public void succeed(AdmixedData admixedData) {
        if(admixedData!=null){
            getDialog().getProgressHelper().hideProgress();
            getDialog().setContentText("数据量过大 请耐心等待...");
            this.admixedData = admixedData;
            initData();
        }else {
            dismissDialog();
        }
    }

    @Override
    public Map<String, String> getParams() {
        //StyleID=121280|121281|121282|121283|121284|116742|116743|120256|116744|118384|118385|116745|116746&IsDiff=1&sign=BAAB78139F449B600AA0505285492DFE&tokenID=6&userId=3
        Map<String,String> params = new HashMap<>();
        params.put("userId", AppContext.getContext().getUser().getUserId()+"");
//        params.put("userId", "51");
        params.put("StyleID", styleIdsParam);
        params.put("IsDiff", IsDiff);
        params.put("tokenID", "6");
        params = MD5Utils.encryptParams(params);
        return params;
    }

    //TODO 参配对比选择车型后的处理
    /**
     * 从车型确认处传过来的车型信息
     * @param newStyle
     */
  /*  @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(NewStyle newStyle) {
        if(newStyle==null){
            return;
        }else{
            if(newStyle.isCancel()){
                return;
            }
            AppManager.getAppManager().finishActivity(AdmixedContrastActivity.class);

            localCarConfigModel.setStyleId(Integer.valueOf(newStyle.getStyleId()));
            localCarConfigModel.setStyleName(newStyle.getName());
            localCarConfigModel.setNowMsrp(Double.valueOf(newStyle.getNowMsrp()));
            localCarConfigModel.setFullName(newStyle.getName()+" "+newStyle.getYear()+"款"+Double.valueOf(newStyle.getNowMsrp()) +"万元");
            tvTitle.setText(localCarConfigModel.getFullName());
        }
    }*/

}
